<?php
namespace app\common\service;

use think\Model;

class CoursePushTplService extends BaseService
{

    /**
     * 后台 获取课程推送模版列表
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getCoursePushTplList($sid)
    {
        $field = 'id,tpl_name,add_time';
        $list = db('course_push_tpl')
                ->field($field)
                ->where(['sid' => $sid, 'status' => 1])
                ->order('add_time DESC')
                ->select();

        if($list){
            foreach($list as $k => $v){
                $list[$k]['add_time'] = date('Y-m-d H:i:s', $v['add_time']);

                //查询使用该模版的班级
                $classes = db('classes')->field('name')->where(['sid' => $sid, 'course_push_tpl_id' => $v['id']])->select();
                if($classes){
                    foreach($classes as $ky => $vy){
                        $classes_name[$ky] = $vy['name'];
                    }
                    $list[$k]['classes_name'] = implode('、', $classes_name);
                } else {
                    $list[$k]['classes_name'] = '';
                }
            }
        }
        return $list;
    }

    /**
     * 后台 新增或编辑课程推送模版
     * @param int $id
     * @param $sid
     * @param array $postData
     * @return array
     * @throws \think\Exception
     */
    public function saveCoursePushTpl($id = 0, $sid, $postData = [])
    {
        $data = [
            'tpl_name' => $postData['tpl_name'],
            'forecast_push_later_type' => $postData['forecast_push_later_type'],
            'forecast_push_later_interval' => $postData['forecast_push_later_interval'],
            'forecast_push_later_weekday' => $postData['forecast_push_later_weekday'] ? implode(',', $postData['forecast_push_later_weekday']) : '',
            'forecast_push_later_time' => $postData['forecast_push_later_time'],
            'forecast_push_limit' => $postData['forecast_push_limit']
//            'notice_push_before_day' => $postData['notice_push_before_day'],
//            'notice_push_time' => $postData['notice_push_time']
        ];
        if($postData['notice_push_before_day'] && $postData['notice_push_before_day'] != -1){
            $data['notice_push_before_day'] = implode(',', $postData['notice_push_before_day']);
            $data['notice_push_time'] = $postData['notice_push_time'];
        } else {
            $data['notice_push_before_day'] = -1;
            $data['notice_push_time'] = 0;
        }

        if($id){
            //是否重名
            $info = db('course_push_tpl')->where(['id' => ['<>', $id], 'sid' => $sid, 'tpl_name' => $postData['tpl_name'], 'status' => 1])->find();
            if($info){
                return ['status' => 0, 'msg' => '该模版已存在'];
            }
            $data['edit_time'] = time();
            $r = db('course_push_tpl')->where(['id' => $id])->update($data);
        } else {
            $data['sid'] = $sid;
            $data['add_time'] = time();
            $r = db('course_push_tpl')->insert($data);
        }
        return $r === false ? ['status' => 0, 'msg' => '保存失败'] : ['status' => 1, 'msg' => '保存成功'];
    }


    /**
     * 后台 删除课程推送模版
     * @param $sid
     * @param $id
     * @return array
     */
    public function deleteCoursePushTpl($sid, $id)
    {
        //查询是否有使用的
        $info = db('course_push_task')->where(['sid' => $sid, 'course_push_tpl_id' => $id, 'status' => ['<>', -1]])->find();
        if($info){
            return ['status' => 0, 'msg' => '该模版正在被使用，无法删除'];
        }
        $r = db('course_push_tpl')->where(['sid' => $sid, 'id' => $id])->setField('status', -1);
        return $r === false ? ['status' => 0, 'msg' => '删除失败'] : ['status' => 1, 'msg' => '删除成功'];
    }


    /**
     * 后台 获取课程推送模版详情
     * @param $sid
     * @param $id
     * @return array|false|\PDOStatement|string|Model
     */
    public function getCoursePushTplDetail($sid, $id)
    {
        $filed = 'id,tpl_name,forecast,forecast_push_later_type,forecast_push_later_interval,forecast_push_later_weekday,
        forecast_push_later_time,forecast_push_limit,notice,notice_push_before_day,notice_push_time';
        $where = [
            'sid' => $sid,
            'id' => $id,
            'status' => 1
        ];
        $info = db('course_push_tpl')->field($filed)->where($where)->find();
        if($info['forecast_push_later_weekday']){
            $info['forecast_push_later_weekday'] = explode(',', $info['forecast_push_later_weekday']);
        }
        if($info['notice_push_before_day'] != -1){
            $info['notice_push_before_day'] = explode(',', $info['notice_push_before_day']);
        }
        return $info;
    }


    /**
     * 后台: 添加课程推送模版任务
     * @param $sid
     * @param $course_id
     * @param array $class_ids
     * @param int $course_push_tpl_id
     * @param $add_flag
     * @return int|string
     * @throws \think\Exception
     */
    public function addCoursePushTask($sid, $course_id, $class_ids = [], $course_push_tpl_id = 0, $add_flag, $using_class_setting_push)
    {
       /* $course_push_tpl_ids = [];
        if($class_ids){
            //查询班级添加的课程推送模版ID
            $classes = db('classes')
                        ->field('classid,course_push_tpl_id')
                        ->where(['sid' => $sid, 'classid' => ['in', $class_ids], 'status' => ['<>', -1]])
                        ->select();
            if($classes){
                foreach($classes as $k => $v){
                    $course_push_tpl_ids[$k] = $v['course_push_tpl_id'];
                }
                //推送模版ID去重
                $course_push_tpl_ids = array_unique($course_push_tpl_id);
            }
        } else {
            if($course_push_tpl_id){
                $course_push_tpl_ids[0] = $course_push_tpl_id;
            }
        }

        if(!$course_push_tpl_ids){
            return false;
        }*/
        if(!$class_ids && !$course_push_tpl_id){
            return false;
        }

        //模版消息是否配置
        $template_info = $this->getCoursePushTemplateInfo($sid);
        if(!$template_info){
            return false;
        }

        if(!$add_flag){
            //更新
            //查询模版任务表中的数据
            $task_where = [
                'sid' => $sid,
                'courseid' => $course_id,
//                'status' => ['<>', -1]
            ];
            $tasks = db('course_push_task')
                    ->where($task_where)
                    ->select();
//            if($using_class_setting_push){
                //使用班级推送模版的情况
                $class_ids_intersect = [];
                if($tasks){
                    foreach($tasks as $key => $val){
                        //使用班级默认的推送模版
                        if(!in_array($val['classid'], $class_ids)){
                            //此条数据与提交上来的数据不相干，则自动设置为取消状态
                            db('course_push_task')->where(['id' => $val['id']])->update(['edit_time' => time(), 'status' => -1]);
                        } else {
                            //此条数据与提交上来的数据相干
                            if($val['status'] == -1){
                                if($using_class_setting_push){
                                    $tpl_id = db('classes')->where(['classid' => $val['classid']])->value('course_push_tpl_id');
                                } else {
                                    $tpl_id = $course_push_tpl_id;
                                }
                                //若为取消状态，则恢复为未开始状态
                                $update_arr = [
                                    'edit_time' => time(),
                                    'status' => 0,
                                    'course_push_tpl_id' => $tpl_id
                                ];
                                db('course_push_task')->where(['id' => $val['id']])->update($update_arr);
                            } else {
                                if(!$using_class_setting_push){
                                    $update_arr = [
                                        'edit_time' => time(),
                                        'status' => 0,
                                        'course_push_tpl_id' => $course_push_tpl_id
                                    ];
                                    db('course_push_task')->where(['id' => $val['id']])->update($update_arr);
                                }
                            }
                            //保存推送任务中的数据和本次提交上来的数据的交集
                            $class_ids_intersect[$key] = $val['classid'];
                        }
                    }
                }
                //求差集
                $class_ids_diff = array_diff($class_ids, $class_ids_intersect);
                if($class_ids_diff){
                    //差集即为需要插入至数据表中的数据
                    $insert_data = [];
                    $flag = true;
                    foreach($class_ids_diff as $kk => $vv){
                        //班级推送模版不为空的情况下插入
                        if($using_class_setting_push){
                            $class_course_push_tpl_id = db('classes')->where(['classid' => $vv])->value('course_push_tpl_id');
                        } else {
                            $class_course_push_tpl_id = $course_push_tpl_id;
                        }

                        $insert_data_1 = [];
                        $insert_data_2 = [];
                        $insert_data_1[$kk] = [
                            'sid' => $sid,
                            'courseid' => $course_id,
                            'classid' => $vv,
                            'wx_template_no' => $template_info['template_no'],
                            'course_push_tpl_id' => $class_course_push_tpl_id,
                            'push_content' => $this->getCoursePushContent($sid, $course_id, $template_info, 1),
                            'push_type' => 1,
                            'add_time' => time(),
                            'status' => 0
                        ];
                        $insert_data_2[$kk] =  [
                            'sid' => $sid,
                            'courseid' => $course_id,
                            'classid' => $vv,
                            'wx_template_no' => $template_info['template_no'],
                            'course_push_tpl_id' => $class_course_push_tpl_id,
                            'push_content' => $this->getCoursePushContent($sid, $course_id, $template_info, 2),
                            'push_type' => 2,
                            'add_time' => time(),
                            'status' => 0
                        ];
                        //插入两条任务数据 一条为推送课程预告，一条为推送课程通知
                        $insert_data = array_merge_recursive($insert_data_1, $insert_data_2);

                        if(!$insert_data){
                            $flag = false;
                            continue;
                        }
                        $r = db('course_push_task')->insertAll($insert_data);
                        if(!$r){
                            $flag = false;
                        }
                    }
                    return $flag;
                }
            /*} else {
                //使用自定义推送模版的情况
                if($tasks){
                    $def_flag = false;
                    foreach($tasks as $ky => $vy){
                        if($vy['classid'] == 0){
                            $def_flag = true;
                            //添加了自定义模版，修改为其他自定义模版的情况，只修改模版ID即可
                            //注意:classid=0的数据至多只有一条
                            $df_update_data = ['edit_time' => time(), 'course_push_tpl_id' => $course_push_tpl_id];
                            if($vy['status'] == -1){
                                $df_update_data['status'] = 0;
                            }
                            db('course_push_task')
                                ->where(['id' => $vy['id']])
                                ->update($df_update_data);
                        } else {
                            //其他情况则自动取消
                            db('course_push_task')->where(['id' => $vy['id']])->update(['edit_time' => time(), 'status' => -1]);
                        }
                    }
                    //任务表中不存在自定义模版数据，则插入新数据
                    if(!$def_flag){
                        $insert_data[0] = [
                            'sid' => $sid,
                            'courseid' => $course_id,
                            'classid' => 0,
                            'wx_template_no' => $template_info['template_no'],
                            'course_push_tpl_id' => $course_push_tpl_id,
                            'push_content' => $this->getCoursePushContent($sid, $course_id, $template_info, 1),
                            'push_type' => 1,
                            'add_time' => time(),
                            'status' => 0
                        ];
                        $insert_data[1] = [
                            'sid' => $sid,
                            'courseid' => $course_id,
                            'classid' => 0,
                            'wx_template_no' => $template_info['template_no'],
                            'course_push_tpl_id' => $course_push_tpl_id,
                            'push_content' => $this->getCoursePushContent($sid, $course_id, $template_info, 2),
                            'push_type' => 2,
                            'add_time' => time(),
                            'status' => 0
                        ];
                        return db('course_push_task')->insertAll($insert_data);
                    }
                } else {
                    $insert_data[0] = [
                        'sid' => $sid,
                        'courseid' => $course_id,
                        'classid' => 0,
                        'wx_template_no' => $template_info['template_no'],
                        'course_push_tpl_id' => $course_push_tpl_id,
                        'push_content' => $this->getCoursePushContent($sid, $course_id, $template_info, 1),
                        'push_type' => 1,
                        'add_time' => time(),
                        'status' => 0
                    ];
                    $insert_data[1] = [
                        'sid' => $sid,
                        'courseid' => $course_id,
                        'classid' => 0,
                        'wx_template_no' => $template_info['template_no'],
                        'course_push_tpl_id' => $course_push_tpl_id,
                        'push_content' => $this->getCoursePushContent($sid, $course_id, $template_info, 2),
                        'push_type' => 2,
                        'add_time' => time(),
                        'status' => 0
                    ];
                    return db('course_push_task')->insertAll($insert_data);
                }
            }*/

        } else {
//            if($using_class_setting_push){
                $insert_data = [];
                $flag = true;
                foreach($class_ids as $kk => $vv){
                    $insert_data_1 = [];
                    $insert_data_2 = [];
                    //班级推送模版不为空的情况下插入
//                    $class_course_push_tpl_id = db('classes')->where(['classid' => $vv])->value('course_push_tpl_id');
                    if($using_class_setting_push){
                        $class_course_push_tpl_id = db('classes')->where(['classid' => $vv])->value('course_push_tpl_id');
                    } else {
                        $class_course_push_tpl_id = $course_push_tpl_id;
                    }
                    $insert_data_1[$kk] = [
                        'sid' => $sid,
                        'courseid' => $course_id,
                        'classid' => $vv,
                        'wx_template_no' => $template_info['template_no'],
                        'course_push_tpl_id' => $class_course_push_tpl_id,
                        'push_content' => $this->getCoursePushContent($sid, $course_id, $template_info, 1),
                        'push_type' => 1,
                        'add_time' => time(),
                        'status' => 0
                    ];
                    $insert_data_2[$kk] =  [
                        'sid' => $sid,
                        'courseid' => $course_id,
                        'classid' => $vv,
                        'wx_template_no' => $template_info['template_no'],
                        'course_push_tpl_id' => $class_course_push_tpl_id,
                        'push_content' => $this->getCoursePushContent($sid, $course_id, $template_info, 2),
                        'push_type' => 2,
                        'add_time' => time(),
                        'status' => 0
                    ];
                    $insert_data = array_merge_recursive($insert_data_1, $insert_data_2);
                    if(!$insert_data){
                        $flag = false;
                        continue;
                    }
                    $r = db('course_push_task')->insertAll($insert_data);
                    if(!$r){
                        $flag = false;
                    }
                }
                return $flag;
            /*} else {
                $insert_data[0] = [
                    'sid' => $sid,
                    'courseid' => $course_id,
                    'classid' => 0,
                    'wx_template_no' => $template_info['template_no'],
                    'course_push_tpl_id' => $course_push_tpl_id,
                    'push_content' => $this->getCoursePushContent($sid, $course_id, $template_info, 1),
                    'push_type' => 1,
                    'add_time' => time(),
                    'status' => 0
                ];
                $insert_data[1] = [
                    'sid' => $sid,
                    'courseid' => $course_id,
                    'classid' => 0,
                    'wx_template_no' => $template_info['template_no'],
                    'course_push_tpl_id' => $course_push_tpl_id,
                    'push_content' => $this->getCoursePushContent($sid, $course_id, $template_info, 2),
                    'push_type' => 2,
                    'add_time' => time(),
                    'status' => 0
                ];
                return db('course_push_task')->insertAll($insert_data);
            }*/
        }

    }

    /**
     * 获取课程推送模版的微信模版ID和推送内容
     * @param $sid
     * @return mixed
     */
    private function getCoursePushTemplateInfo($sid)
    {
        $template_type = 322;
        $where = [
            'sid' => $sid,
            'template_type' => $template_type,
            'status' => 1
        ];
        return db('wx_template')->field('template_no,template_config')->where($where)->find();
    }


    /**
     * 获取课程推送内容
     * @param $sid
     * @param $course_id
     * @param $template_info
     * @param $push_type
     * @return string
     */
    private function getCoursePushContent($sid, $course_id, $template_info, $push_type)
    {
        $course_info = db('course')->field('name,speaker,schooltime,courseid')->where(['courseid' => $course_id])->find();
        $wxTplMsgService = new WxTplMsgService();
        $data = [
            'cid' => 0,
            'courseid' => $course_id
        ];
        $send_data['url'] = $push_type == 1 ? $wxTplMsgService->getTemplateLinkUrl($sid, 10, $data) : '';
        $send_data['data'] = $wxTplMsgService->parseTemplateCfg($template_info, $course_info, 2);
        return json_encode($send_data, JSON_UNESCAPED_UNICODE);
    }


    /**
     * 后台: 获取课程推送任务列表
     * @param $sid
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getNormalCoursePushTaskList($sid)
    {
        $list = db('course_push_task')
                ->where(['sid' => $sid, 'status' => 0, 'classid' => ['>', 0]])
                ->order('id DESC')
                ->select();
        //模版ID可能存在更换的情况，所以单独查询
        $template_info = $this->getCoursePushTemplateInfo($sid);
        $template_no = $template_info['template_no'];

        $data = [];
        if($list){
            foreach($list as $k => $v){
                //获取推送模版信息
                $push_tpl = db('course_push_tpl')->where(['id' => $v['course_push_tpl_id'], 'status' => 1])->find();
                if($push_tpl && $this->checkPushTask($sid, $v['courseid'], $v['push_type'], $push_tpl)){
                    //判断课程通知是否设置过
                    if($v['push_type'] == 2 && $push_tpl['notice_push_before_day'] == -1){
                        continue;
                    }
                    $v['push_tpl'] = $push_tpl;
                    $v['wx_template_no'] = $template_no;
                    $data[] = $v;
                }
            }
        }
        return $data;
    }


    /**
     * 后台: 判断该任务是否推送
     * @param $sid
     * @param $course_id
     * @param $push_type
     * @param array $push_tpl
     * @return bool
     */
    private function checkPushTask($sid, $course_id, $push_type, $push_tpl = [])
    {
        $course_info = db('course')
                    ->field('schooltime,addtime')
                    ->where(['sid' => $sid, 'courseid' => $course_id, 'course_status' => 1])
                    ->find();
        if(!$course_info){
            return false;
        }

        //时间区间为课程发布时间至课程开课时间
        $cur_time = time(); //保存当前请求时间
        $begin_time = $course_info['addtime']; //时间区间中的开始时间
        $begin_time_0 = strtotime(date('Y-m-d', $begin_time)); //开始时间的当天0点的时间戳
        $begin_time_24 = strtotime(date('Y-m-d', $begin_time)) + 86400; //开始时间的当天24点的时间戳
        $begin_week = date('w', $begin_time) == 0 ? 7 : date('w', $begin_time); //开始当天是星期几
        $end_time = $course_info['schooltime']; //时间区间中的结束时间
        $end_time_0 = strtotime(date('Y-m-d', $end_time)); //时间区间中的结束时间的0点时间戳

        //请求时间大于课程开课时间无须再推送
//        if($cur_time > $end_time || $cur_time < $begin_time_24){
        if($cur_time > $end_time){
            return false;
        }

        $cur_time_0 = strtotime(date('Y-m-d', $cur_time)); //请求时间的当天0点时间戳
        $cur_week = date('w') == 0 ? 7 : date('w'); //当前请求是星期几 0代表星期天，直接替换成7

        //是否为立即发布的课程，立即发送的课程则直接推送
        if($begin_time_0 == $cur_time_0){
            return true;
        }

        $limit = $push_tpl['forecast_push_limit']; //课程预告推送次数限制 -1代表不限
        $interval = $push_tpl['forecast_push_later_interval']; //课程预告推送间隔
        $forecast_push_type = $push_tpl['forecast_push_later_type']; //课程预告推送类型 1:按天; 2:按周
        $forecast_push_time = $push_tpl['forecast_push_later_time']; //课程预告当天推送时间 几点
        $notice_push_day = $push_tpl['notice_push_before_day']; //课程通知 提前几天推送，-1代表未设置
        $notice_push_time = $push_tpl['notice_push_time']; //课程通知推送时间 几点

        if($push_type == 1){
            //课程预告
            if($forecast_push_type == 1){
                //按天
                if($interval == 0){
                    //每天都发送
                    $push_time = $forecast_push_time * 3600;
                    $day_push_time = $cur_time_0 + $push_time;

                    //若做了推送次数限制,判断当前应该推送的次数
                    if($limit != -1){
                        $push_count = ($cur_time_0 - $begin_time_0) / 86400;
                        if($push_count > $limit){
                            return false;
                        }
                    }

                    //请求时间超过当天推送的时间
                    if($cur_time > $day_push_time){
                        return false;
                    }
                } else {
                    //有天数间隔的发送
                    $interval_day = ($cur_time_0 - $begin_time_0)/86400;
                    if($interval_day != ($interval+1)){
                        return false;
                    }

                    //若做了推送次数限制,判断当前应该推送的次数
                    if($limit != -1){
                        $push_count = floor($interval_day/($interval + 1)); //间隔天数除以间隔时间，并向下取整
                        if($push_count > $limit){
                            return false;
                        }
                    }

                    $flag = false;
                    for($i = 0; $i < $limit; $i++){
                        $push_time_0 = $begin_time_24 + $interval * 86400; //间隔X天的当天0点时间戳
                        $push_time = $forecast_push_time * 3600;
                        $day_push_time = $push_time_0 + $push_time; //间隔X天的当天需推送的时间戳
                        //若请求时间介于两者之间 则推送
                        if($cur_time > $push_time_0 && $cur_time < $day_push_time){
                            $flag = true;
                        }
                    }
                    if($flag == false){
                        return false;
                    }
                }
            } else {
                //按周
                if(!$push_tpl['forecast_push_later_weekday']){
                    return false;
                }
                $forecast_push_weekday = explode(',', $push_tpl['forecast_push_later_weekday']); //保存星期几推送,数组,可能是多选
                $cur_interval_week = floor(($cur_time - $begin_time)/(7*24*3600)); //保存发布的课程至当前时间隔几周

                if($interval != 0){
                    //间隔几周发送的情况
                    if($cur_interval_week != $interval){
                        return false;
                    }
                }

                //当前星期几，若不再推送的星期几里面里面，则不推送
                if(!in_array($cur_week, $forecast_push_weekday)){
                    return false;
                }

                //若做了推送次数限制,判断当前应该推送的次数
                if($limit != -1){
                    $begin_sunday_time = $begin_time_24 + (7 - $begin_week) * 86400; //发布课程当周星期天24点时间戳
                    $push_count = 0; //保存到当前应当推送的次数

                    foreach($forecast_push_weekday as $k => $v){
                        if($begin_week < $cur_week){
                            $push_count += 1;
                        }
                    }

                    if($cur_time > $begin_sunday_time){
                        //发布课程之后的一周开始计算
                        foreach($forecast_push_weekday as $key => $val){
                            if($val <= $cur_week){
                                $push_count += 1;
                            }
                        }
                        //计算到当前总共推送的次数
                        $push_count = $cur_interval_week * count($forecast_push_weekday) + $push_count;
                    }
                    if($push_count > $limit){
                        return false;
                    }
                }

                $push_time = $forecast_push_time * 3600;
                $day_push_time = $cur_time_0 + $push_time;
                //请求时间超过当天推送的时间
                if($cur_time > $day_push_time){
                    return false;
                }
            }
        } else {
            //课程通知
            if($notice_push_day == -1){
                return false;
            }
            $push_time = $notice_push_time * 3600;
            //推送时间区间开始点
            $push_start_time = $end_time_0 - $notice_push_day * 24 * 3600;
            //推送时间区间结束点
            $push_end_time = $push_start_time + $push_time;
            if($cur_time < $push_start_time || $cur_time > $push_end_time){
                return false;
            }
        }
        return true;
    }


    /**
     * 后台: 获取推送通知记录列表
     * @param $sid
     * @param $course_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getPushRecordList($sid, $course_id)
    {
        $field = 'tr.id,tr.courseid,tr.begin_time,tr.total_num,tr.success_num';
        $where = [
            't.push_type' => 1, //推送类型(1:课程预告;2:课程通知)，只统计课程预告
            'tr.sid' => $sid,
            'tr.courseid' => $course_id
        ];
        $list = db('course_push_task_record tr')
                ->field($field)
                ->join('course_push_task t', 'tr.course_push_task_id=t.id')
                ->where($where)
                ->order('tr.begin_time DESC')
                ->select();
        if($list){
            foreach ($list as $k => $v) {
                $list[$k]['begin_time'] = date('Y-m-d H:i', $v['begin_time']);

                $logs = db('course_push_task_log')->where(['sid' => $sid, 'task_record_id' => $v['id']])->select();
                $open_num = 0; //打开人数
                $uncertainty_num = 0; //不确定人数
                $certainty_num = 0; //确定人数
                $not_num = 0; //确定不来
                if($logs){
                    foreach($logs as $key => $val){
                        //统计打开人数
                        if($val['open_status'] == 1){
                            $open_num += 1;
                        }
                        if($val['operate_status'] == 1){
                            $certainty_num += 1;
                        } elseif($val['operate_status'] == 2){
                            $not_num += 1;
                        } elseif($val['operate_status'] == 3){
                            $uncertainty_num += 1;
                        }
                    }
                }
                $list[$k]['open_num'] = $open_num;
                $list[$k]['certainty_num'] = $certainty_num;
                $list[$k]['uncertainty_num'] = $uncertainty_num;
                $list[$k]['not_num'] = $not_num;
            }
        }
        return $list;
    }


    /**
     * 后台: 获取推送记录人员列表
     * @param $sid
     * @param $record_id
     * @param $status
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getPushRecordUserList($sid, $record_id, $status, $p, $pageSize){
        $filed = 'tl.studentsid,tl.uid,tl.send_status,tl.open_status,tl.operate_status,u.user_headimgurl,u.user_nickname,s.name,s.phone';
        $where = [
            'tl.sid' => $sid,
            'tl.task_record_id' => $record_id
        ];
        switch($status){
            case 1:
                break;
            case 2:
                //成功送达
                $where['tl.send_status'] = 1;
                break;
            case 3:
                //打开人数
                $where['tl.open_status'] = 1;
                break;
            case 4:
                //不确定要来
                $where['tl.operate_status'] = 3;
                break;
            case 5:
                //确定要来
                $where['tl.operate_status'] = 1;
                break;
            case 6:
                //确定不来
                $where['tl.operate_status'] = 2;
                break;
            default:
                break;
        }

        $list = db('course_push_task_log tl')
            ->field($filed)
            ->join('students s', 's.id=tl.studentsid', 'LEFT')
            ->join('user u', 's.uid=u.user_id', 'LEFT')
            ->where($where)
            ->group($filed)
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->select();

        $count = db('course_push_task_log tl')
            ->join('students s', 's.id=tl.studentsid', 'LEFT')
            ->join('user u', 's.uid=u.user_id', 'LEFT')
            ->where($where)
            ->group($filed)
            ->count();
        $data = [
            'page' => [
                'count' => $count
            ],
            'content' => $list
        ];

        return $data;
    }


    /**
     * 微信端: 获取推送统计中的课程列表
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getCourseListStatistics($sid, $p, $pageSize){
        $course_list = db('course')
                        ->field('courseid,name,speaker,schooltime')
                        ->where(['sid' => $sid, 'schooltime' => ['>', time()], 'course_status' => 1])
                        ->order('schooltime ASC')
                        ->limit(($p - 1) * $pageSize, $pageSize)
                        ->select();
        if($course_list){
            foreach($course_list as $k => $v){
                $course_list[$k]['schooltime'] = date('Y.m.d', $v['schooltime']);
                $course_list[$k]['speaker'] = json_decode($v['speaker'], 1);

                $detail = $this->getCourseDetailCommonStatistics($sid, $v['courseid']);
                $course_list[$k] = array_merge_recursive($course_list[$k], $detail);
            }
        }
        return $course_list;
    }


    /**
     * 微信端: 获取课程详情统计
     * @param $sid
     * @param $course_id
     * @return array|false|\PDOStatement|string|Model
     */
    public function getCourseDetailStatistics($sid, $course_id){
        $course_info = db('course')
                        ->field('courseid,name,speaker,schooltime')
                        ->where(['sid' => $sid, 'courseid' => $course_id])
                        ->find();
        if(!$course_info){
            return false;
        }
        $course_info['speaker'] = json_decode($course_info['speaker'], 1);
        $statistics_detail = $this->getCourseDetailCommonStatistics($sid, $course_id);
        $course_info = array_merge_recursive($course_info, $statistics_detail);
        return $course_info;
    }

    private function getCourseDetailCommonStatistics($sid, $course_id){
        $detail = [];
        $push_detail_list = db('course_push_task_detail')->where(['sid' => $sid, 'courseid' => $course_id])->order('id ASC')->select();
        if($push_detail_list){
            $total_num = [];
            $success_num = [];
            $certainty_num = [];
            $uncertainty_num = [];
            $not_num = [];
            $not_open_num = [];
            $push_count = $push_detail_list[0]['push_count']; //保存最近推送的次数
            $push_latest_time = $push_detail_list[0]['add_time']; //保存最近推送的时间
            foreach($push_detail_list as $key => $val){
                //以uid为数组下标
                $total_num[$val['studentsid']] = $val;
                //送达
                if($val['send_status'] == 1){
                    $success_num[$val['studentsid']] = $val;
                    //未打开
                    if($val['open_status'] == 0){
                        $not_open_num[$val['studentsid']] = $val;
                    }
                    //确认来
                    if($val['operate_status'] == 1){
                        $certainty_num[$val['studentsid']] = $val;
                    }
                    //确认不来
                    if($val['operate_status'] == 2){
                        $not_num[$val['studentsid']] = $val;
                    }
                    //不确定来不来
                    if($val['operate_status'] == 3){
                        $uncertainty_num[$val['studentsid']] = $val;
                    }
                }

                //当前推送次数
                if($key > 0){
                    if($val['push_count'] > $push_detail_list[$key-1]['push_count']){
                        $push_count = $val['push_count'];
                        $push_latest_time = $val['add_time'];
                    }
                }
            }
            $detail['push_count'] = $push_count;
            $detail['push_latest_time'] = $push_latest_time ? date('Y.m.d H:i', $push_latest_time) : 0;
            $detail['total_num'] = count($total_num);
            $detail['success_num'] = count($success_num);
            $detail['certainty_num'] = count($certainty_num);
            $detail['not_num'] = count($not_num);
            $detail['uncertainty_num'] = count($uncertainty_num);
            $detail['not_open_num'] = count($not_open_num);
        } else {
            $detail['total_num'] = 0;
            $detail['success_num'] = 0;
            $detail['certainty_num'] = 0;
            $detail['not_num'] = 0;
            $detail['uncertainty_num'] = 0;
            $detail['push_count'] = 0;
            $detail['push_latest_time'] = 0;
            $detail['not_open_num'] = 0;
        }
        return $detail;
    }


    /**
     * 微信端: 获取课程详情统计的学员列表
     * @param $sid
     * @param $uid
     * @param $course_id
     * @param $status
     * @param int $self
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getCourseDetailUserStatistics($sid, $uid, $course_id, $status, $self=0, $p, $pageSize){
        $field = 'td.studentsid,td.uid,s.name,s.phone,u.user_headimgurl,u.user_nickname';
        $where = [
            'td.sid' => $sid,
            'td.courseid' => $course_id
        ];
        if($self == 1){
            $where['ui.parent_id|ui.counselor_id'] = $uid;
        }
        switch($status){
            case 1:
                //未送达
                $where['td.send_status'] = 0;
                break;
            case 2:
                //未打开
                $where['td.send_status'] = 1;
                $where['td.open_status'] = 0;
                break;
            case 3:
                //确定要来
                $where['td.send_status'] = 1;
                $where['td.operate_status'] = 1;
                break;
            case 4:
                //确定不来
                $where['td.send_status'] = 1;
                $where['td.operate_status'] = 2;
                break;
            case 5:
                //不确定要来
                $where['td.send_status'] = 1;
                $where['td.operate_status'] = 3;
                break;
            default:
                break;
        }

        $list = db('course_push_task_detail td')
                ->field($field)
                ->join('students s', 's.id=td.studentsid', 'LEFT')
                ->join('user_integral ui', 'ui.userid=s.uid', 'LEFT')
                ->join('user u', 'u.user_id=s.uid', 'LEFT')
                ->where($where)
                ->group('td.studentsid,td.uid,s.name,s.phone,u.user_headimgurl,u.user_nickname')
                ->limit(($p - 1) * $pageSize, $pageSize)
                ->select();

        return $list;
    }
}